package com.example.springsecurity.authentication;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;

import java.util.Collections;

/**
 * @Author: anwenbiao
 * @Description: TODO
 * @DateTime: 2023/2/4 23:24
 */

@Slf4j
public class SmsAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;
    
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //手机号
        String phone = (String) authentication.getPrincipal();
        //验证码
        String code = (String) authentication.getCredentials();
        log.info("手机号：【{}】,验证码【{}】",phone,code);
        if(!StringUtils.pathEquals("0000",code)){
            throw new BadCredentialsException("验证码错误");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(phone);
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("当前手机号不存在");
        }
        SmsAuthenticationToken smsAuthenticationToken = new SmsAuthenticationToken(phone,code, Collections.emptyList());
        smsAuthenticationToken.setDetails(authentication.getDetails());
        return smsAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
